package com.yanqu.road.server.manger.activity.shuihuyezicard;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.shuihuyezipai.ShuiHuYeZiCardCalExtraResult;
import com.yanqu.road.entity.activity.shuihuyezipai.ShuiHuYeZiCardGetCardResult;
import com.yanqu.road.entity.activity.shuihuyezipai.config.*;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.logic.bussiness.activity.ShuiHuYeZiCardBusiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.activity.ShuiHuYeZiCardProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.shuihuyezicard.ShuiHuYeZiCardModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.*;

/**
 * @Description 水浒叶子牌
 * @Author cwq
 * @Data 2021/12/3 16:00
 */
public class ShuiHuYeZiCardMgr extends TempMgr {

    public static int ACTIVITY_CHILD_TYPE = 1;

    private static ActivityInfo activityInfo;

    /**
     * 配置
     */
    private static ShuiHuYeZiCardActivityConfig config;

    private static RandomHelper random = new RandomHelper();

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    public static void reloadActivityData() {
        getLogger().info("reload ShuiHuYeZiCard Activity start");
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.ShuiHuYeZiCardActivity.getValue());
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no ShuiHuYeZiCard Activity in show time");
            activityInfo = null;
            config = null;
        }else {
            ActivityInfo tempActivityInfo = openActivityInfoList.get(0);

            List<Integer> activityIdList = new ArrayList<>();
            activityIdList.add(tempActivityInfo.getActivityId());

            Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(activityIdList).get(tempActivityInfo.getActivityId());
            ShuiHuYeZiCardActivityConfig tempShuiHuYeZiCardConfig = new ShuiHuYeZiCardActivityConfig();
            tempShuiHuYeZiCardConfig.setCardConfigMap(ShuiHuYeZiCardBusiness.getShuiHuYeZiCardCardConfigMap(tempActivityInfo.getActivityId()));
            tempShuiHuYeZiCardConfig.setBuffConfigMap(ShuiHuYeZiCardBusiness.getShuiHuYeZiCardBuffConfigMap(tempActivityInfo.getActivityId()));
            tempShuiHuYeZiCardConfig.setLevelConfigMap(ShuiHuYeZiCardBusiness.getShuiHuYeZiCardLevelConfigMap(tempActivityInfo.getActivityId()));
            tempShuiHuYeZiCardConfig.setRoomConfigMap(ShuiHuYeZiCardBusiness.getShuiHuYeZiCardRoomConfigMap(tempActivityInfo.getActivityId()));

            ShuiHuYeZiCardActivityConfig.parseConfig(tempShuiHuYeZiCardConfig,activityConfigMap,tempActivityInfo);


            config = tempShuiHuYeZiCardConfig;
            activityInfo = tempActivityInfo;
        }
        for (GamePlayer gamePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            ShuiHuYeZiCardModule shuiHuYeZiCardModule = gamePlayer.getModule(ShuiHuYeZiCardModule.class);
            shuiHuYeZiCardModule.sendConfigToClient();
            shuiHuYeZiCardModule.initUserData();
            shuiHuYeZiCardModule.synUserData();
        }
        getLogger().info("reload ShuiHuYeZiCard Activity finish");
    }

    @Override
    public boolean stop() {
        return true;
    }


    /**
     * 是否玩家可以进入活动
     */
    public static int canEntryActivity(GamePlayer player,int activityId) {
        if(!ActivityMgr.activityInShowTime(ShuiHuYeZiCardMgr.getActivityInfo())){
            return GameErrorCode.E_SHUIHUYEZICARD_ACTIVITY_NO_OPEN;
        }
        if(!SystemOpenMgr.systemOpen(player, eSystemId.ShuiHuYeZiCardActivity.getValue())){
            return GameErrorCode.E_SHUIHUYEZICARD_ACTIVITY_NO_UNLOCK;
        }
        if(ShuiHuYeZiCardMgr.getActivityInfo() == null || ShuiHuYeZiCardMgr.getActivityInfo().getActivityId() != activityId){
            return GameErrorCode.E_SHUIHUYEZICARD_ACTIVITY_NO_OPEN;
        }
        return 0;
    }

    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public static ShuiHuYeZiCardActivityConfig getConfig() {
        return config;
    }

    /**
     *  抽卡
     *  特殊规则 玩家第一次五抽 必得金卡
     * @param player
     * @param type  0单次 1五次
     * @return
     */
    public static List<ShuiHuYeZiCardProto.ShuiHuYeZiCardGetCardResult> randomCard(GamePlayer player, int type){
        ShuiHuYeZiCardModule shuiHuYeZiCardModule = player.getModule(ShuiHuYeZiCardModule.class);
        List<ShuiHuYeZiCardProto.ShuiHuYeZiCardGetCardResult> list = new ArrayList();
        List<ShuiHuYeZiCardGetCardResult> resultList = new ArrayList<>();
        HashSet<Integer> addCardSet = new HashSet<>();
        int cardNum = 0;
        if(type == 0){
            cardNum = 1;
        }else {
            cardNum = 5;
            if(shuiHuYeZiCardModule.getUserData().getContGetCardTimes() == 0){
                ShuiHuYeZiCardCardConfig cardConfig = ShuiHuYeZiCardMgr.getConfig().getGoldProbabilityItems().nextItem();
                resultList.add(new ShuiHuYeZiCardGetCardResult(cardConfig.getId(),1));
                addCardSet.add(cardConfig.getId());
                cardNum--;
            }
            shuiHuYeZiCardModule.getUserData().setContGetCardTimes(shuiHuYeZiCardModule.getUserData().getContGetCardTimes() + 1);
        }
        for (int i = 0; i < cardNum; i++) {
            int total = 0;
            for (ShuiHuYeZiCardCardConfig item : ShuiHuYeZiCardMgr.getConfig().getCardConfigMap().values()){
                if(addCardSet.contains(item.getId())){
                    continue;
                }
                total += item.getGoldWeight();
                total += item.getWeight();
            }
            int value = random.next(total);
            for (ShuiHuYeZiCardCardConfig item : ShuiHuYeZiCardMgr.getConfig().getCardConfigMap().values()){
                if(addCardSet.contains(item.getId())){
                    continue;
                }
                if(value < item.getGoldWeight()){
                    // 金卡  如果已有金卡 转换为指定数量普通卡  普通卡升
                    resultList.add(new ShuiHuYeZiCardGetCardResult(item.getId(),1));
                    addCardSet.add(item.getId());
                    break;
                }
                value -= item.getGoldWeight();
                if(value < item.getWeight()){
                    // 普通卡
                    resultList.add(new ShuiHuYeZiCardGetCardResult(item.getId(),0));
                    addCardSet.add(item.getId());
                    break;
                }
                value -= item.getWeight();
            }
        }
        int totalIntegral = 0;
        long now = DateHelper.getCurrentTime();
        for (ShuiHuYeZiCardGetCardResult item : resultList){
            // 加的积分
            int addIntegral = shuiHuYeZiCardModule.addCard(item,type,now);

            ShuiHuYeZiCardProto.ShuiHuYeZiCardGetCardResult.Builder result = ShuiHuYeZiCardProto.ShuiHuYeZiCardGetCardResult.newBuilder();
            result.setId(item.getId());
            result.setQuality(item.getQuality());
            result.setScore(addIntegral);
            list.add(result.build());
            totalIntegral += addIntegral;
        }
        shuiHuYeZiCardModule.addIntegral(totalIntegral,eLogMoneyType.ShuiHuYeZiCardActivityGetCardGetIntegral);
        return list;
    }

    public static ShuiHuYeZiCardProto.SyncShuiHuYeZiConfigRespMsg.Builder builderSyncShuiHuYeZiConfigRespMsg(){
        ShuiHuYeZiCardProto.SyncShuiHuYeZiConfigRespMsg.Builder builder = ShuiHuYeZiCardProto.SyncShuiHuYeZiConfigRespMsg.newBuilder();
        for (ShuiHuYeZiCardBuffConfig item : config.getBuffConfigMap().values()){
            ShuiHuYeZiCardProto.ShuiHuYeZiCardBuffConfig.Builder buffConfig = ShuiHuYeZiCardProto.ShuiHuYeZiCardBuffConfig.newBuilder();
            buffConfig.setId(item.getId());
            buffConfig.setType(item.getType());
            buffConfig.setPar(item.getPar());
            buffConfig.setRound(item.getRound());
            buffConfig.setWeight(item.getWeight());
            builder.addBuffConfigList(buffConfig);
        }
        for (ShuiHuYeZiCardCardConfig item : config.getCardConfigMap().values()){
            ShuiHuYeZiCardProto.ShuiHuYeZiCardCardConfig.Builder cardConfig = ShuiHuYeZiCardProto.ShuiHuYeZiCardCardConfig.newBuilder();
            cardConfig.setId(item.getId());
            cardConfig.setType(item.getType());
            cardConfig.setPoint(item.getPoint());
            cardConfig.setUpgradeCondition(item.getUpgradeCondition());
            cardConfig.setUpgradePoint(item.getUpgradePoint());
            cardConfig.setScore(item.getScore());
            cardConfig.setGoldWeight(item.getGoldWeight());
            cardConfig.setWeight(item.getWeight());
            builder.addCardConfigList(cardConfig);
        }
        for (ShuiHuYeZiCardLevelConfig item : config.getLevelConfigMap().values()){
            ShuiHuYeZiCardProto.ShuiHuYeZiCardLevelConfig.Builder levelConfig = ShuiHuYeZiCardProto.ShuiHuYeZiCardLevelConfig.newBuilder();
            levelConfig.setId(item.getId());
            levelConfig.setScore(item.getScore());
            levelConfig.setSucceedScore(item.getSucceedScore());
            levelConfig.setDefeatScore(item.getDefeatScore());
            levelConfig.setSucceedRate(item.getSucceedRate());
            levelConfig.setAccuracyAI(item.getAccuracyAI());
            builder.addLevelConfigList(levelConfig);
        }
        for (ShuiHuYeZiCardRoomConfig item : config.getRoomConfigMap().values()){
            ShuiHuYeZiCardProto.ShuiHuYeZiCardRoomConfig.Builder roomConfig = ShuiHuYeZiCardProto.ShuiHuYeZiCardRoomConfig.newBuilder();
            roomConfig.setId(item.getId());
            roomConfig.setType(item.getType());
            roomConfig.setConsume(item.getConsume());
            roomConfig.setSucceedReward(item.getSucceedReward());
            roomConfig.setDefeatReward(item.getDefeatReward());
            roomConfig.setFreePlay(item.getFreePlay());
            roomConfig.setCondition(item.getCondition());
            roomConfig.setTicketsCondition(item.getTicketsCondition());
            roomConfig.setScoreParam(item.getScoreParam());
            builder.addRoomConfigList(roomConfig);
        }
        return builder;
    }

    public static void offLine(GamePlayer player){
        if(!ActivityMgr.activityInShowTime(ShuiHuYeZiCardMgr.getActivityInfo())){
            return ;
        }
        if(!SystemOpenMgr.systemOpen(player, eSystemId.ShuiHuYeZiCardActivity.getValue())){
            return ;
        }
        ShuiHuYeZiCardModule shuiHuYeZiCardModule = player.getModule(ShuiHuYeZiCardModule.class);
        if(shuiHuYeZiCardModule.getStatus() != 0 || shuiHuYeZiCardModule.getPvpRoomId() != 0){
            // 离线
            player.sendPacket(new YanQuMessage(CrossProtocol.C_CROSS_SHUIHUYEZICARD_PVP_OFFLINE));
        }
    }

    /**
     * 计算额外加成
     * @param winStreakNum   连胜次数
     * @param remainCardNum  剩余手牌数
     * @return
     */
    public static ShuiHuYeZiCardCalExtraResult calExtraRankScore(int winStreakNum,int remainCardNum, int scoreParam){
        // 连胜加成  叶子牌连胜分加成：min(当前连胜 - 1 ,系数1)*系数2/1000，向下取整
        winStreakNum = Math.max(0, winStreakNum - 1 );
        int winStreakNumPlus = Math.min(winStreakNum,ShuiHuYeZiCardMgr.getConfig().winStreakCoefficientList.get(0)) * ShuiHuYeZiCardMgr.getConfig().winStreakCoefficientList.get(1) / 1000;
        winStreakNumPlus = winStreakNumPlus * scoreParam;
        // 手牌加成  叶子牌手牌分加成：剩余手牌*系数1/1000，向下取整
        int remainCardPlus = remainCardNum * ShuiHuYeZiCardMgr.getConfig().SHUIHUYEZICARD_REMAIN_CARD_PLUS_COEFFICIENT / 1000;
        remainCardPlus = remainCardPlus * scoreParam;

        int totalPlus = winStreakNumPlus + remainCardPlus ;

        ShuiHuYeZiCardCalExtraResult result = new ShuiHuYeZiCardCalExtraResult();
        result.setWinStreakNum(winStreakNum);
        result.setRemainCardPlus(remainCardPlus);
        result.setTotalPlus(totalPlus);
        return result;
    }


    public static void sendSettlement(int type, GamePlayer player,boolean isWin,String reward,int oldRankScore, int curRankScore,int winStreakNum,int winStreakNumPlus, int remainCardPlus){
        ShuiHuYeZiCardProto.BroadcastShuiHuYeZiCardRespMsg.Builder broadcast = ShuiHuYeZiCardProto.BroadcastShuiHuYeZiCardRespMsg.newBuilder();
        ShuiHuYeZiCardProto.ShuiHuYeZiCardSettlement.Builder settlement = ShuiHuYeZiCardProto.ShuiHuYeZiCardSettlement.newBuilder();
        settlement.setIsWin(isWin);
        settlement.setReward(reward);
        settlement.setOldRankScore(oldRankScore);
        settlement.setCurRankScore(curRankScore);
        settlement.setWinningStreakNum(winStreakNum);
        settlement.setWinStreakNumPlus(winStreakNumPlus);
        settlement.setRemainCardPlus(remainCardPlus);
        broadcast.setSettlement(settlement);
        broadcast.setType(type);
        player.sendPacket(ClientProtocol.U_SHUIHUYEZICARD_BROADCAST,broadcast);
    }

    /**
     * 取消匹配
     * @param player
     * @param roomId
     */
    public static void cancelMatch(GamePlayer player,int roomId){
        ShuiHuYeZiCardRoomConfig roomConfig = ShuiHuYeZiCardMgr.getConfig().getRoomConfigMap().get(roomId);
        if(roomConfig != null){
            Property consume = PropertyHelper.parseStringToProperty(roomConfig.getConsume());
            // 解除预扣除
            player.getModule(PreReduceModule.class).restorePreReduce(consume);
        }
        player.getModule(ShuiHuYeZiCardModule.class).setStatus(0);
    }

    /**
     * 送福奖励
     * @param player
     * @return
     */
    public static Property getDisperseGoldReward(GamePlayer player){
        //银两奖励
        int totalSilver = random.next(ShuiHuYeZiCardMgr.getConfig().giveMoneySecondsList.get(0), ShuiHuYeZiCardMgr.getConfig().giveMoneySecondsList.get(1));
        totalSilver = totalSilver > GameConfig.DISPERSE_GOLD_MAX_SILVER ? GameConfig.DISPERSE_GOLD_MAX_SILVER : totalSilver;
        BigInteger silver = player.getUserInfo().getEarnSpeed().multiply(BigInteger.valueOf(totalSilver));

        Property property = new Property();
        property.addProperty(GameConfig.GAME_MONEY_SILVER, silver);
        property.addProperty(PropertyHelper.parseStringToProperty(ShuiHuYeZiCardMgr.getConfig().SHUIHUYEZICARD_GIVE_MONEY_REWARDS));
        return property;
    }


    public static ActivityInfo getOpenActivityInfo(int activityId){
        if(ActivityMgr.activityInShowTime(activityInfo) && activityInfo.getActivityId() == activityId){
            return activityInfo;
        }
        return null;
    }

    /**
     * 加斗牌奖励
     * @param player
     * @param reward
     * @param son
     */
    public static void addReward(GamePlayer player,String reward,eLogMoneyType son){
        Property property = PropertyHelper.parseStringToProperty(reward);
        BigInteger integer = property.removeProperty(eItemId.SHUIHUYEZICARD_INTEGRAL_ITEM.getValue());
        player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.ShuiHuYeZiCardActivity, son);
        // 加积分
        if(integer != null){
            player.getModule(ShuiHuYeZiCardModule.class).addIntegral(integer.intValue(),son);
        }

    }


    /**
     * 运营需要的抽卡数据
     */
//    @Deprecated
//    public static void test(GamePlayer player) throws Exception{
//        ShuiHuYeZiCardModule shuiHuYeZiCardModule = player.getModule(ShuiHuYeZiCardModule.class);
//        List<String> list = new ArrayList<>();
//        int type = 1;
//        for (int i = 0; i < 10; i++) {
//            String s = "第"+i+"轮";
//            list.add(s);
//            shuiHuYeZiCardModule.getUserData().getCardMap().clear();
//            while (shuiHuYeZiCardModule.getCardTotalLevel() < 60){
//                List<ShuiHuYeZiCardProto.ShuiHuYeZiCardGetCardResult> resultList = ShuiHuYeZiCardMgr.randomCard(player,type);
//                for (ShuiHuYeZiCardProto.ShuiHuYeZiCardGetCardResult item : resultList){
//                    s = "cardId: "+item.getId()+",quality:"+item.getQuality()+",score:"+item.getScore()+",升级后的level:"+shuiHuYeZiCardModule.getUserData().getCardMap().get(item.getId()).getLevel()+",升级后的num:"+shuiHuYeZiCardModule.getUserData().getCardMap().get(item.getId()).getNum()+"";
//                    list.add(s);
//                }
//            }
//        }
//        FileOperateHelper.writeFileContent("D:\\getCardTest.txt",list);
//    }

}
